package com.gang.lingdian.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author gyg
 * @date 2022/11/13 13:13
 * desc Nio服务端
 */
public class NioServer {
    // 保存客户端连接
    static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        // 创建NIO ServerSocketChannel  相当于BIO SocketServe
        ServerSocketChannel socketServer = ServerSocketChannel.open();
        socketServer.socket().bind(new InetSocketAddress(9000));
        // 设置为非阻塞
        socketServer.configureBlocking(false);
        System.out.println("NIO 服务端启动成功");

        while (true){
            SocketChannel socketChannel = socketServer.accept();
            if(socketChannel != null){
                System.out.println("连接成功");
                socketChannel.configureBlocking(false);
                channelList.add(socketChannel);
            }
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()){
                SocketChannel channel = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                // 非阻塞模式read方法不会阻塞，否则会阻塞
                int len = channel.read(byteBuffer);
                if(len>0){
                    System.out.println("接收到消息："+ new String(byteBuffer.array()));
                } else if (len == -1){
                    iterator.remove();
                    System.out.println("客户端断开连接");
                }
            }
        }

    }
}
